package com.xbx.eurekaserver.listener;

import com.google.gson.Gson;
import com.xbx.baseweb.entity.email.EmailParam;
import com.xbx.baseweb.entity.email.EmailSendResult;
import com.xbx.baseweb.service.EmailService;
import com.xbx.common.utils.HttpClientUtil;
import com.xbx.common.utils.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * eureka服务状态监听器
 *
 * @author 89005691
 * @create 2018-11-05 15:21
 */
@Component
@Slf4j
public class EurekaStateChangeListener {

    @Autowired
    private EmailService emailService;

    @Value("${xbx.message.templateCode}")
    private String templateCode;

    @EventListener
    public void listen(EurekaInstanceCanceledEvent eurekaInstanceCanceledEvent) {

        String appName = eurekaInstanceCanceledEvent.getAppName();
        String serverId = eurekaInstanceCanceledEvent.getServerId();

        EmailParam emailParam = new EmailParam();

        Map<String, Object> map = new HashMap<>();

        map.put("appName", appName);
        map.put("serverId", serverId);
        map.put("shutdownTime", MyUtils.changeTimeByParam(MyUtils.generateTime(), MyUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));

        emailParam.setModel(map);

        // 发送消息
        EmailSendResult result = emailService.send(emailParam, "server-status-template.html");

        if (result != null) {

            if (result.getCode() == 0) {

                log.info("发送邮件成功");
            } else {

                log.error("eureka服务状态监听器发送邮件返回状态码：{}，错误结果：{}", result.getCode(), result.getMsg());
            }
        } else {

            log.error("eureka服务状态监听器发送邮件失败");
        }
    }
}